<?php
/**
 * Created by PhpStorm.
 * User: Jasony
 * Date: 2017-12-25
 * Time: 09:54
 */

namespace app\admin\controller;


use app\base\Tools;
use app\common\model\AdminUsers;
use app\common\model\AuthGroupAccess;
use app\common\model\AuthGroups;
use app\common\model\UserProfile;
use think\Db;
use think\Request;
use think\Session;

class User extends BaseController
{
    /***
     * 渲染表格数据
     * @return mixed|\think\response\Json
     * @throws \think\exception\DbException
     */
    public function index()
    {
        if ((Request::instance()->isAjax())) {
            $limit = $this->param['limit'];
            $order_by = $this->param['field']. ' '. $this->param['order'];
            $userModel = new AdminUsers();
            $userData = $userModel
                ->with('userGroup')
                ->field('user_id,user_name,nick_name,head_photo,create_time,status')
                ->order($order_by)
                ->paginate($limit);
            $userData = $userData->toArray();



//            $userData=$userModel->getListForPage([], null, $limit, $order_by)->toArray();
            return Tools::tableData($userData);
        }
        return $this->fetch();
    }

    /***
     * 改变用户状态
     * @return \think\response\Json
     */
    public function changeStatus()
    {
        if (isset($this->param['user_id']) && isset($this->param['is_status'])) {

            $userModel = new AdminUsers();
            $userModel->save(['status'=>$this->param['is_status']],['user_id'=>$this->param['user_id']]);
            return Tools::ajaxReturn(true, '操作成功');
        } else {
            return Tools::ajaxReturn(false, '操作失败');
        }

    }

    /***
     * 删除用户
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function delUser()
    {
        if (isset($this->param['user_id'])) {
            $imgurl = AdminUsers::where('user_id', '=', $this->param['user_id'])
                ->field('head_photo')->find();
            $imgurl = $imgurl->head_photo;
            AdminUsers::destroy($this->param['user_id']);
            UserProfile::destroy($this->param['user_id']);//删除用户资料
            //删除用户旧头像
            unlink(ROOT_PATH . 'public' . DS . 'uploads/admin/avatar/'.$imgurl);
            return Tools::ajaxReturn(true, '操作成功');
        } else {
            return Tools::ajaxReturn(false, '操作失败');
        }

    }

    /***
     * 增加用户
     * @return mixed|\think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function addUser()
    {
        if ((Request::instance()->isPost())) {
            $user = $this->param['user'];
            $pass = $this->param['password'];
            $status = isset($this->param['status']) ? 1 : 0;
            $imgurl = $this->param['imgurl'];
            $nick = $this->param['nick'];

            $username=AdminUsers::get(['user_name' => $user]);
            if (isset($username->user_name)) {
                return Tools::ajaxReturn(false,'用户已存在');

            }

            $userModel = new AdminUsers();
            $userModel->user_name = $user;
            $userModel->password = md5($pass);
            $userModel->nick_name = $nick;
            $userModel->head_photo = $imgurl;
            $userModel->status= $status;
            $userModel->save();
            $uid = $userModel->user_id;
            if (isset($this->param['auth'])) {
                $aut_access = new AuthGroupAccess();
                foreach ($this->param['auth'] as $value) {
                    $aut_access->uid  = $uid;
                    $aut_access->group_id= $value;
                    $aut_access->save();
                }
            }
            return Tools::ajaxReturn(true,'添加成功');
        }
        $groups = new AuthGroups();
        $this->assign('groups',$groups->field('id,title')->select()->toArray());
        return $this->fetch();
    }

    /***
     * 用户资料
     * @return mixed|string
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function profile()
    {


        if (isset($this->param['uid'])) {
            $uid = $this->param['uid'];
        }else{
            $uid = Session::get('user.user_id');//用户UID
        }

        if ((Request::instance()->isPost())) {


            $userObj = new AdminUsers();
            if (!isset($this->param['change_pass'])) {
                $userObj->save(['password'=>md5($this->param['change_pass'])], ['user_id'=>$uid]);
            }
            if (!isset($this->param['imgurl'])) {

                $imgurl = AdminUsers::where('user_id', '=', $uid)
                    ->field('head_photo')->find();
                $imgurl = $imgurl->head_photo;
                unlink(ROOT_PATH . 'public' . DS . 'uploads/admin/avatar/'.$imgurl);
                $userObj->save(['head_photo'=>$this->param['imgurl']],['user_id'=>$uid]);
            }

            $table = config('database.prefix');
            $table = $table . 'user_profile';
            $columns = Db::query('SHOW FULL COLUMNS FROM '.$table);

            if (!is_null(UserProfile::get($uid))) {
                //存在资料 需要更新资料
                $profile = UserProfile::get($uid);
                foreach ($columns as $v) {
                    if ($v['Field']=='user_id') {
                        continue;
                    }
                    $profile->$v['Field'] = $this->param[$v['Field']];
                }
                $profile->save();
            }else{
                //不存在资料 需要新增资料
                $profile = new UserProfile();
                $profile->user_id = $uid;
                foreach ($columns as $v) {
                    if ($v['Field']=='user_id') {
                        continue;
                    }
                    $profile->$v['Field'] = $this->param[$v['Field']];
                }
                $profile->save();
            }

            return Tools::ajaxReturn(true, '修改成功');
        }




        $table = config('database.prefix');
        $table = $table . 'user_profile';
        $columns = Db::query('SHOW FULL COLUMNS FROM '.$table);
        $userProfileDate = UserProfile::get($uid);
        if (!is_null($userProfileDate)) {
            $userProfileDate= $userProfileDate->toArray();
        }
        $head_img = new AdminUsers();
        $head_img = $head_img->field('head_photo')->where('user_id', $uid)->find()->head_photo;
        if ((Request::instance()->isPost())) {
            return 'post';
        }
        $this->assign('form', $columns);
        $this->assign('head_img', $head_img);
        $this->assign('profileData',$userProfileDate);
        return $this->fetch();
    }


    public function auth()
    {

        if (Request::instance()->isAjax()) {
            $auth_id = $this->param['auth'];
            $value= $this->param['value'];
            $uid= $this->param['uuid'];

            if ($value=='true') {
                AuthGroupAccess::create([
                    'uid' => $uid,
                    'group_id'=>$auth_id
                ]);

                return 'ok';

            }else{
                $au = new AuthGroupAccess();
                $au->where('uid', $uid)->where('group_id', $auth_id)->delete();
                return 'ok';

            }
        }


        $access = new AuthGroupAccess();
        $group = new AuthGroups();
        $access_arr = $access->where('uid', $this->param['uid'])->field('group_id')->select()->toArray();
        $auth_groups=$group->field('id,title,description')->select()->toArray();
        $access_arr = arr_foreach($access_arr);
        foreach ($auth_groups as $k=>$v) {
            if (in_array($v['id'], $access_arr)) {
                $auth_groups[$k]['status'] = '1';
            } else {
                $auth_groups[$k]['status'] = '0';
            }
        }
        $this->assign('auth_groups', $auth_groups);
        $this->assign('uid', $this->param['uid']);
        return $this->fetch();
    }
}